<script setup>
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { elementListService, elementAddService, elementUpdateService, elementDeleteService } from '@/api/iimApi/element.js';
import { interfaceListService } from '@/api/iimApi/interface.js';
import { dataTypeListService } from '@/api/biApi/data_types.js';
import { dataSpecificationListService } from '@/api/biApi/data_specifications.js';
import { requirementListService } from '@/api/iimApi/requirement.js';
import { ioTypeListService } from '@/api/biApi/io_types.js';
import { useProjectStore } from '@/stores/projectStore';

// 获取项目存储
const projectStore = useProjectStore();

// 数据元素列表数据模型
const elements = ref([]);
const filteredElements = ref([]);
const elementName = ref('');

// 分页条数据模型
const pageNum = ref(1); // 当前页
const total = ref(0); // 总条数
const pageSize = ref(3); // 每页条数

// 控制抽屉是否显示
const visibleDrawer = ref(false);
const isEdit = ref(false); // 控制是否为编辑状态

// 添加表单数据模型
const elementModel = ref({
  id: null,
  interfaceId: '',
  name: '',
  identifier: '',
  unit: '',
  physicalRange: '',
  valueRange: '',
  exceptionHandling: '',
  encryptionHandling: '',
  precisionRequirement: '',
  dataTypeId: '',
  dataSpecificationId: '',
  correspondingRequirementId: '',
  ioTypeId: '',
  additionalInfo: ''
});

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入数据名称', trigger: 'blur' }],
  identifier: [{ required: true, message: '请输入数据标识', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单位（量纲）', trigger: 'blur' }],
  physicalRange: [{ required: false, message: '请输入物理范围', trigger: 'blur' }],
  valueRange: [{ required: false, message: '请输入值域范围', trigger: 'blur' }],
  exceptionHandling: [{ required: false, message: '请输入异常处理', trigger: 'blur' }],
  encryptionHandling: [{ required: false, message: '请输入加密处理', trigger: 'blur' }],
  precisionRequirement: [{ required: false, message: '请输入经度要求', trigger: 'blur' }],
  additionalInfo: [{ required: false, message: '请输入附加信息', trigger: 'blur' }]
};

// 下拉框数据模型
const interfaces = ref([]);
const dataTypes = ref([]);
const dataSpecifications = ref([]);
const requirements = ref([]);
const ioTypes = ref([]);

// 获取数据元素列表数据
const elementList = async () => {
  let result = await elementListService(projectStore.selectedProject.id);

  // 渲染视图
  elements.value = result.data.map(item => ({
    id: item.id,
    interfaceId: item.interfaceId,
    name: item.name,
    identifier: item.identifier,
    unit: item.unit,
    physicalRange: item.physicalRange,
    valueRange: item.valueRange,
    exceptionHandling: item.exceptionHandling,
    encryptionHandling: item.encryptionHandling,
    precisionRequirement: item.precisionRequirement,
    dataTypeId: item.dataTypeId,
    dataSpecificationId: item.dataSpecificationId,
    correspondingRequirementId: item.correspondingRequirementId,
    ioTypeId: item.ioTypeId,
    additionalInfo: item.additionalInfo,
    interfaceName: interfaces.value.find(i => i.id === item.interfaceId)?.name || '',
    dataTypeName: dataTypes.value.find(dt => dt.id === item.dataTypeId)?.name || '',
    dataSpecificationName: dataSpecifications.value.find(ds => ds.id === item.dataSpecificationId)?.type || '',
    requirementName: requirements.value.find(r => r.id === item.correspondingRequirementId)?.name || '',
    ioTypeName: ioTypes.value.find(io => io.id === item.ioTypeId)?.type || ''
  }));
  filteredElements.value = elements.value;
  total.value = filteredElements.value.length;
};

// 获取接口列表数据
const getInterfaces = async () => {
  let result = await interfaceListService(projectStore.selectedProject.id);
  interfaces.value = result.data;
};

// 获取数据类型列表数据
const getDataTypes = async () => {
  let result = await dataTypeListService();
  dataTypes.value = result.data;
};

// 获取数据规格列表数据
const getDataSpecifications = async () => {
  let result = await dataSpecificationListService();
  dataSpecifications.value = result.data;
};

// 获取需求列表数据
const getRequirements = async () => {
  let result = await requirementListService(projectStore.selectedProject.id);
  requirements.value = result.data;
};

// 获取IO类型列表数据
const getIoTypes = async () => {
  let result = await ioTypeListService();
  ioTypes.value = result.data;
};

// 初始化数据
const initData = async () => {
  await getInterfaces();
  await getDataTypes();
  await getDataSpecifications();
  await getRequirements();
  await getIoTypes();
  await elementList();
};

// 计算当前页显示的数据
const paginatedElements = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredElements.value.slice(start, end);
});

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  elementList();
};

// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  elementList();
};

// 过滤数据元素列表
const filterElements = () => {
  const query = elementName.value.toLowerCase();
  filteredElements.value = elements.value.filter(element => 
    element.name.toLowerCase().includes(query) || 
    element.identifier.toLowerCase().includes(query)
  );
  total.value = filteredElements.value.length;
};

// 重置搜索
const resetSearch = () => {
  elementName.value = '';
  filterElements();
};

// 添加数据元素
const addElement = async () => {
  let result;
  if (isEdit.value) {
    result = await elementUpdateService(elementModel.value, projectStore.selectedProject.id);
    ElMessage.success(result.msg ? result.msg : '修改成功');
  } else {
    result = await elementAddService(elementModel.value, projectStore.selectedProject.id);
    ElMessage.success(result.msg ? result.msg : '添加成功');
  }
  visibleDrawer.value = false;
  elementList();
};

// 编辑数据元素
const editElement = (elementItem) => {
  isEdit.value = true;
  elementModel.value = { ...elementItem };
  visibleDrawer.value = true;
};

// 删除数据元素
const deleteElement = async (elementItem) => {
  try {
    await ElMessageBox.confirm(
      `此操作将永久删除数据元素 "${elementItem.name}" 的信息, 是否继续?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    await elementDeleteService(elementItem.id, projectStore.selectedProject.id);
    ElMessage.success('删除成功');
    elementList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 初始化数据元素列表
initData();
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>数据元素定义管理</span>
        <div class="extra">
          <el-button type="primary" @click="() => { isEdit = false; visibleDrawer = true; }">添加数据元素</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="数据名称或标识：">
        <el-input placeholder="请输入数据名称或标识" v-model="elementName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="filterElements">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据元素信息列表 -->
    <el-table :data="paginatedElements" style="width: 100%">
      <el-table-column prop="name" label="数据名称" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="interfaceName" label="所属接口" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="identifier" label="数据标识" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="unit" label="单位（量纲）" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="physicalRange" label="物理范围" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="valueRange" label="值域范围" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="exceptionHandling" label="异常处理" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="encryptionHandling" label="加密处理" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="precisionRequirement" label="经度要求" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="dataTypeName" label="数据类型" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="dataSpecificationName" label="数据规格" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="requirementName" label="对应需求" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="ioTypeName" label="IO类型" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="additionalInfo" label="附加信息" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button @click="editElement(scope.row)" type="primary" size="small">修改</el-button>
          <el-button @click="deleteElement(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="isEdit ? '修改数据元素' : '添加数据元素'" direction="rtl" size="50%">
      <!-- 添加数据元素表单 -->
      <el-form :model="elementModel" :rules="rules" label-width="100px">
        <el-form-item label="所属接口">
          <el-select v-model="elementModel.interfaceId" placeholder="请选择所属接口">
            <el-option
              v-for="interfaceItem in interfaces"
              :key="interfaceItem.id"
              :label="interfaceItem.name"
              :value="interfaceItem.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据名称" prop="name">
          <el-input v-model="elementModel.name" placeholder="请输入数据名称"></el-input>
        </el-form-item>
        <el-form-item label="数据标识" prop="identifier">
          <el-input v-model="elementModel.identifier" placeholder="请输入数据标识"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="elementModel.unit" placeholder="请输入单位（量纲）"></el-input>
        </el-form-item>
        <el-form-item label="物理范围" prop="physicalRange">
          <el-input type="textarea" v-model="elementModel.physicalRange" placeholder="请输入物理范围"></el-input>
        </el-form-item>
        <el-form-item label="值域范围" prop="valueRange">
          <el-input type="textarea" v-model="elementModel.valueRange" placeholder="请输入值域范围"></el-input>
        </el-form-item>
        <el-form-item label="异常处理" prop="exceptionHandling">
          <el-input type="textarea" v-model="elementModel.exceptionHandling" placeholder="请输入异常处理"></el-input>
        </el-form-item>
        <el-form-item label="加密处理" prop="encryptionHandling">
          <el-input type="textarea" v-model="elementModel.encryptionHandling" placeholder="请输入加密处理"></el-input>
        </el-form-item>
        <el-form-item label="经度要求" prop="precisionRequirement">
          <el-input type="textarea" v-model="elementModel.precisionRequirement" placeholder="请输入经度要求"></el-input>
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select v-model="elementModel.dataTypeId" placeholder="请选择数据类型">
            <el-option
              v-for="dataType in dataTypes"
              :key="dataType.id"
              :label="dataType.name"
              :value="dataType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据规格">
          <el-select v-model="elementModel.dataSpecificationId" placeholder="请选择数据规格">
            <el-option
              v-for="dataSpecification in dataSpecifications"
              :key="dataSpecification.id"
              :label="dataSpecification.type"
              :value="dataSpecification.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="对应需求">
          <el-select v-model="elementModel.correspondingRequirementId" placeholder="请选择对应需求">
            <el-option
              v-for="requirement in requirements"
              :key="requirement.id"
              :label="requirement.name"
              :value="requirement.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="IO类型">
          <el-select v-model="elementModel.ioTypeId" placeholder="请选择IO类型">
            <el-option
              v-for="ioType in ioTypes"
              :key="ioType.id"
              :label="ioType.type"
              :value="ioType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="附加信息" prop="additionalInfo">
          <el-input type="textarea" v-model="elementModel.additionalInfo" placeholder="请输入附加信息"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addElement">{{ isEdit ? '修改' : '添加' }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>